import express from 'express';
import Sequelize from 'sequelize';
import { Checkin, User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, addMoney } from '../../utils/utils'; // 工具类
import messageApi from '../../lib/messageapi'; // 消息通知相关API
import CONFIG from '../../../config/config.config'; // 全局配置

const router = express.Router();

router.get('/', async function (Request, Response, next) {
  // let param = Request.query

  let checkinNumber = 0 // 今日签到数
  let sumGold = 0 // 今日用户总积分数

  await countCheckin(Response).then(res => {
    checkinNumber = res
  })

  await countGold(Response).then(res => {
    sumGold = res
  })

  Checkin.Modal.destroy({
    where: {},
    truncate: true,
  }).then(res => {
    messageApi.serverJiang({
      text: `${CONFIG.appNameC}用户签到请理成功`,
      desp: `今日总签到人数：${checkinNumber}人，用户积分总和：${sumGold}`
    }).then(() => {
      Response.json({
        data: '',
        message: "success"
      });
    })
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function countCheckin(Response) {
  // 计算今日签到用户数
  return new Promise((resolve, reject) => {
    Checkin.Modal.findAll().then(res => {
      resolve(res.length)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function countGold(Response) {
  // 计算用户积分总额
  return new Promise((resolve, reject) => {
    User.Modal.sum('gold').then(sum => {
      resolve(sum)
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;